﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TwitterMatic.Shared;
using TwitterMatic.Shared.Data;
using System.Web.Caching;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

namespace TwitterMatic_WebRole.Code.ActionHelpers
{
    public class StatisticsViewDataAttribute : ActionFilterAttribute
    {
        public const string TOTALTWEETS = "Statistics_TotalTweets";

        protected IConfigurationProvider configuration;
        protected ITimedTweetRepository repository;

        protected IConfigurationProvider Configuration
        {
            get
            {
                if (configuration == null)
                {
                    configuration = new AzureConfigurationProvider();
                }
                return configuration;
            }
            set
            {
                configuration = value;
            }
        }

        protected ITimedTweetRepository Repository
        {
            get
            {
                if (repository == null)
                {
                    CloudStorageAccount cloudStorageAccount = CloudStorageAccount.FromConfigurationSetting("StorageConnection");
                    CloudTableClient tableClient = cloudStorageAccount.CreateCloudTableClient();
                    tableClient.CreateTableIfNotExist("TimedTweet");

                    repository = new TimedTweetRepository(tableClient);
                }
                return repository;
            }
            set
            {
                repository = value;
            }
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext.HttpContext.Cache.Get(TOTALTWEETS) == null)
            {
                filterContext.HttpContext.Cache.Add(TOTALTWEETS, Repository.CountAll(), null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
            }

            filterContext.Controller.ViewData.Add(TOTALTWEETS, filterContext.HttpContext.Cache.Get(TOTALTWEETS));

            base.OnActionExecuted(filterContext);
        }
    }
}
